package com.ts.audiocamera

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.opengl.GLES20
import android.opengl.GLException
import android.os.Bundle
import android.widget.Button
import android.widget.ImageView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.ts.opengl.EGL
import java.nio.IntBuffer

class EGLActivity : AppCompatActivity() {
    lateinit var img:ImageView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_eglactivity)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        var bitmap=BitmapFactory.decodeResource(resources,R.drawable.cdemo)
        var mEGL= EGL()
        mEGL.init(this);
        img=findViewById(R.id.act_img_view)

        findViewById<Button>(R.id.clcik).setOnClickListener {

            mEGL.setImageView(bitmap)
            mEGL.draw(bitmap.width,bitmap.height);
            img.setImageBitmap(createBitmapFromGLSurface(0, 0, bitmap.width, bitmap.height))
        }
    }


    companion object{
        @JvmStatic
        public fun createBitmapFromGLSurface(x: Int, y: Int, w: Int, h: Int): Bitmap? {
            val bitmapBuffer = IntArray(w * h)
            val bitmapSource = IntArray(w * h)
            val intBuffer = IntBuffer.wrap(bitmapBuffer)
            intBuffer.position(0)
            try {
                GLES20.glReadPixels(
                    x, y, w, h, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE,
                    intBuffer
                )
                var offset1: Int
                var offset2: Int
                for (i in 0 until h) {
                    offset1 = i * w
                    offset2 = (h - i - 1) * w
                    for (j in 0 until w) {
                        val texturePixel = bitmapBuffer[offset1 + j]
                        val blue = (texturePixel shr 16) and 0xff
                        val red = (texturePixel shl 16) and 0x00ff0000
                        val pixel = (texturePixel and -0xff0100) or red or blue
                        bitmapSource[offset2 + j] = pixel
                    }
                }
            } catch (e: GLException) {
                return null
            }
            return Bitmap.createBitmap(bitmapSource, w, h, Bitmap.Config.ARGB_8888)
        }
    }

}